package com.platform.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.util.TransactionUtil;
import com.platform.helper.string.IdUtil;
import com.platform.system.entity.SysFile;
import com.platform.system.entity.SysPrivilege;
import com.platform.system.entity.SysPrivilegeFile;
import com.platform.system.enums.PrivilegeTypeEnum;
import com.platform.system.mapper.SysFileMapper;
import com.platform.system.service.SysFileService;
import com.platform.system.service.SysPrivilegeFileService;
import com.platform.system.service.SysPrivilegeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;

import javax.annotation.Resource;

/**
 * describe:
 *
 * @author rainly
 * @date 2019/12/07
 * @time 7:13 下午
 */
@Slf4j
@Service
public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFile> implements SysFileService {

    @Resource
    private SysFileMapper sysFileMapper;

    @Resource
    private SysPrivilegeFileService sysPrivilegeFileService;

    @Resource
    private SysPrivilegeService sysPrivilegeService;

    @Resource
    private TransactionUtil transactionUtil;


    @Override
    public boolean save(SysFile entity) {
        String fileId = IdUtil.nextIdStr();
        String privilegeId = IdUtil.nextIdStr();

        SysPrivilege sysPrivilege = new SysPrivilege();
        SysPrivilegeFile sysPrivilegeFile = new SysPrivilegeFile();

        entity.setFileId(fileId);

        sysPrivilegeFile.setFileId(fileId);
        sysPrivilegeFile.setPrivilegeId(privilegeId);

        sysPrivilege.setPrivilegeId(privilegeId);
        sysPrivilege.setPrivilegeName(entity.getFileName());
        sysPrivilege.setPrivilegeType(PrivilegeTypeEnum.file.name());
        TransactionStatus ts = transactionUtil.open();

        boolean isSave = super.save(entity) &&
                         sysPrivilegeService.save(sysPrivilege) &&
                         sysPrivilegeFileService.save(sysPrivilegeFile);
        if (isSave){
            if (ts != null) {
                transactionUtil.commit(ts);
            }
            log.info("保存文件成功，文件名："+ entity.getFileName() + ",文件路径：" + entity.getFilePath());
        }else {
            if (ts != null) {
                transactionUtil.rollback(ts);
            }
            log.error("保存文件失败，文件名："+ entity.getFileName() + ",文件路径：" + entity.getFilePath());
        }
        return isSave;
    }
}
